package com.tiantian.novel.resolver.impl;

import com.tiantian.novel.helper.HttpHelper;
import com.tiantian.novel.model.ChapterInfo;
import com.tiantian.novel.model.NovelSummary;
import com.tiantian.novel.resolver.NovelResolver;
import org.jsoup.nodes.Element;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.util.stream.Collectors;

/**
 * Sina
 *
 * @author wangk21
 * @date 2023/11/26.
 */
public class SinaBlogNovelResolver implements NovelResolver {
    private static final Logger log = LoggerFactory.getLogger(BiqugeNewNovelResolver.class);
    /**
     * http utils
     */
    private HttpHelper http;

    public SinaBlogNovelResolver() {
        this.http = new HttpHelper(true);
    }

    @Override
    public NovelSummary resolveNovelSummary(String url) throws Exception {
        return null;
    }

    @Override
    public ChapterInfo resovleChapter(String url) throws Exception {
        log.info("resovle ChapterInfo from www 【{}】", url);
        Element body = http.getBody(url);
        if (body == null || body.text().contains("系统维护中，博文仅作者可见。登陆后可查看本人文章。")) {
            log.info("body is null");
            return null;
        }
        Element title = body.selectFirst("div.articalTitle > h2.titName");
        if (title == null) {
            log.info("title is null");
            return null;
        }

        Element container = body.selectFirst("div#sina_keyword_ad_area2");
        if (container == null) {
            log.info("container is null");
            return null;
        }

        String contentText = container.select("font")
                .stream()
                .map(p -> {
                    return "<p>" + p.text().trim() + "</p>";
                })
                .filter(StringUtils::hasText)
                .collect(Collectors.joining("\n"));
        System.out.println(contentText);
        ChapterInfo info = new ChapterInfo(0, url, title.text().trim().split("\\(")[0]);
        info.setContent(contentText);
        return info;
    }

    @Override
    public byte[] getImage(String logo) throws IOException {
        return http.getImage(logo);
    }
}
